﻿/*
 * This file was automatically created by adding project item of type
 *    Common SharePoint Extension Method 
 *    
 * Look for the project at http://spcommonextensions.codeplex.com
 * 
 * File Version:
 *      v0.1.0
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$

namespace $rootnamespace$
{
	internal static partial class $safeitemrootname$
    {
        /// <summary>
        /// This method saves a time stamp for controls. With that you can check for POST safety. If a POST is processed a new ID will be generated for the 
        /// control and it is saved in the server session. On POST the method checks the ID stored in the control context. If it is equal to the session
        /// stored ID the POST is safe. If it is not equal the POST was already processed.
        /// </summary>
        /// <param name="control">The web control</param>
        /// <example>
        /// bool saveToProcess = !button.IsPostPack || button.IsPostSave;
        /// if( saveToProcess ) {
        ///     ...
        /// }
        /// </example>
        /// <returns>true = POST save</returns>
        internal static bool IsPostSave(this System.Web.UI.WebControls.WebControl control)
        {
            bool IsPOSTSave = false;

            if( !control.Page.IsPostBack )
            {
            }
            else
            {
                IsPOSTSave = control.Attributes["POSTSaveId"] != (string)HttpContext.Current.Session[control.ID]
                                ||
                             ( control.Attributes["POSTSaveId"] == null && HttpContext.Current.Session[control.ID] == null );
                if( IsPOSTSave )
                {
                    HttpContext.Current.Session[control.ID] = control.Attributes["POSTSaveId"];
                }
            }

            control.Attributes.Add("POSTSaveId", Guid.NewGuid().ToString());

            return IsPOSTSave;
        }

        /// <summary>
        /// Linq Extension to get the index of an object in an array using a comparer.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="array"></param>
        /// <param name="comparer"></param>
        /// <returns></returns>
        public static int FindIndex<T>(this IEnumerable<T> array, Func<T, bool> comparer)
        {
            if( array == null )
                throw new ArgumentNullException("items");
            if( comparer == null )
                throw new ArgumentNullException("predicate");

            int retVal = 0;
            foreach( var item in array )
            {
                if( comparer(item) )
                    return retVal;
                retVal++;
            }
            return -1;
        }

        /// <summary>
        /// Linq extension to get the index of an object in an erray.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="array"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public static int IndexOf<T>(this IEnumerable<T> array, T item)
        {
            return array.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i));
        }

        /// <summary>
        /// Get typed field value of a SharePoint list item
        /// </summary>
        /// <typeparam name="FieldClass"></typeparam>
        /// <typeparam name="FieldValueClass"></typeparam>
        /// <param name="item"></param>
        /// <param name="internalName"></param>
        /// <returns></returns>
        /// <example>
        /// var value listitem.GetTypedFieldValueByInternalName<SPFieldLookup, SPFieldLookupValue>("MyLookupField");
        /// </example>
        internal static FieldValueClass GetTypedFieldValueByInternalName<FieldClass, FieldValueClass>(this SPListItem item, string internalName) where FieldClass : SPField
        {
            var f = (FieldClass)item.Fields.GetFieldByInternalName(internalName);
            return ( (FieldValueClass)( f ).GetFieldValue(item[f.Id].ToString()) );
        }

        /// <summary>
        /// Get field value of SharePoint list item by internal name.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="internalName"></param>
        /// <returns></returns>
        internal static string GetFieldValueByInternalName(this SPListItem item, string internalName)
        {
            var f = (SPField)item.Fields.GetFieldByInternalName(internalName);
            return (string)item[f.Id];
        }

        /// <summary>
        /// Get list by web relative URL.
        /// </summary>
        /// <param name="web"></param>
        /// <param name="listRelativeWebUrl"></param>
        /// <returns></returns>
        /// <example>
        /// web.GetListByWebRelativeURL("Lists
        /// </example>
        internal static SPList GetListByWebRelativeURL(this SPWeb web, string listRelativeWebUrl)
        {
            var l = web.GetList(string.Concat(web.ServerRelativeUrl.TrimEnd('/'),"/",listRelativeWebUrl.TrimStart('/')));
            return l;
        }

        /// <summary>
        /// Add list item event receiver
        /// </summary>
        /// <param name="list"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="singleEvents"></param>
        /// <param name="synchronization"></param>
        public static void AddListItemEventReceiver(this SPList list, Type eventReceiverType, SPEventReceiverType singleEvents, SPEventReceiverSynchronization synchronization)
        {
            list.AddListItemEventReceiver(eventReceiverType, new SPEventReceiverType[] { singleEvents }, synchronization);
        }

        /// <summary>
        /// Add list item event receiver
        /// </summary>
        /// <param name="list"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="events"></param>
        /// <param name="synchronization"></param>
        public static void AddListItemEventReceiver(this SPList list, Type eventReceiverType, SPEventReceiverType[] events, SPEventReceiverSynchronization synchronization)
        {
            foreach( var thisevent in events )
            {
                SPEventReceiverDefinition r;

                r = list.EventReceivers.Add();
                r.Assembly = eventReceiverType.Assembly.FullName;
                r.Class = eventReceiverType.FullName;
                r.Type = thisevent;

                r.SequenceNumber = 1000;
                r.Synchronization = synchronization;
                r.HostType = SPEventHostType.List;
                r.HostId = list.ID;

                r.Update();
            }

            list.Update();
        }

        /// <summary>
        /// Add list item event receiver to all lists in a web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="events"></param>
        /// <param name="listTemplate"></param>
        /// <param name="synchronization"></param>
        /// <param name="addToHiddenLists"></param>
        public static void AddListItemEventReceiverToAllLists(this SPWeb web, Type eventReceiverType, SPEventReceiverType[] events, SPListTemplateType[] listTemplate, SPEventReceiverSynchronization synchronization, bool addToHiddenLists)
        {
            List<Guid> listguid = new List<Guid>();

            foreach( SPList list in web.Lists )
            {
                if( !list.Hidden || addToHiddenLists )
                {
                    if( listTemplate.Contains(list.BaseTemplate) )
                    {
                        listguid.Add(list.ID);
                    }
                }
            }

            foreach( var g in listguid )
            {
                web.Lists[g].AddListItemEventReceiver(eventReceiverType, events, synchronization);
            }
        }

        /// <summary>
        /// Add list item event receiver to all lists in a web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="singleEvent"></param>
        /// <param name="synchronization"></param>
        public static void AddListItemEventReceiverToAllLists(this SPWeb web, Type eventReceiverType, SPEventReceiverType singleEvent, SPEventReceiverSynchronization synchronization)
        {
            var listTemplateTypes = new SPListTemplateType[]{
                SPListTemplateType.DocumentLibrary,
                SPListTemplateType.GenericList
            };

            web.AddListItemEventReceiverToAllLists(eventReceiverType, new SPEventReceiverType[] { singleEvent }, listTemplateTypes, synchronization, false);
        }

        /// <summary>
        /// Add list item event receiver to all lists in a web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="events"></param>
        /// <param name="synchronization"></param>
        public static void AddListItemEventReceiverToAllLists(this SPWeb web, Type eventReceiverType, SPEventReceiverType[] events, SPEventReceiverSynchronization synchronization)
        {
            var listTemplateTypes = new SPListTemplateType[]{
                SPListTemplateType.DocumentLibrary,
                SPListTemplateType.GenericList
            };
            web.AddListItemEventReceiverToAllLists(eventReceiverType, events, listTemplateTypes, synchronization, false);
        }

        /// <summary>
        /// Remove list item event receiver
        /// </summary>
        /// <param name="list"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="events"></param>
        public static void RemoveListItemEventReceiver(this SPList list, Type eventReceiverType, SPEventReceiverType[] events)
        {
            string c = eventReceiverType.FullName.ToLower();

            List<SPEventReceiverDefinition> rs = new List<SPEventReceiverDefinition>();
            foreach( SPEventReceiverDefinition r in list.EventReceivers )
            {
                if( r.Class.ToLower() == c )
                    rs.Add(r);
            }

            if( rs.Count > 0 )
            {
                foreach( var s in rs )
                {
                    if( events.Contains(s.Type) )
                        s.Delete();
                }

                list.Update();
            }
        }

        /// <summary>
        /// Remove list item event receiver from all lists in a web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="events"></param>
        public static void RemoveListItemEventReceiverFromAllLists(this SPWeb web, Type eventReceiverType, SPEventReceiverType[] events)
        {
            List<Guid> listguid = new List<Guid>();

            foreach( SPList list in web.Lists )
            {
                listguid.Add(list.ID);
            }

            foreach( var g in listguid )
            {
                web.Lists[g].RemoveListItemEventReceiver(eventReceiverType, events);
            }
        }

        /// <summary>
        /// Remove list item event receiver from all lists in a web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="singleEvent"></param>
        public static void RemoveListItemEventReceiverFromAllLists(this SPWeb web, Type eventReceiverType, SPEventReceiverType singleEvent)
        {
            web.RemoveListItemEventReceiverFromAllLists(eventReceiverType, new SPEventReceiverType[] { singleEvent });
        }

        /// <summary>
        /// Remove list item event receiver from all lists in a web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="eventReceiverType"></param>
        public static void RemoveListItemEventReceiverFromAllLists(this SPWeb web, Type eventReceiverType)
        {
            var allListItemEvents = new SPEventReceiverType[] {
                SPEventReceiverType.ItemAdded ,
                SPEventReceiverType.ItemAdding ,
                SPEventReceiverType.ItemAttachmentAdded ,
                SPEventReceiverType.ItemAttachmentAdding ,
                SPEventReceiverType.ItemAttachmentDeleted ,
                SPEventReceiverType.ItemAttachmentDeleting ,
                SPEventReceiverType.ItemCheckedIn ,
                SPEventReceiverType.ItemCheckedOut ,
                SPEventReceiverType.ItemCheckingIn ,
                SPEventReceiverType.ItemCheckingOut ,
                SPEventReceiverType.ItemDeleted ,
                SPEventReceiverType.ItemDeleting ,
                SPEventReceiverType.ItemFileConverted ,
                SPEventReceiverType.ItemFileMoved ,
                SPEventReceiverType.ItemFileMoving ,
                SPEventReceiverType.ItemUncheckedOut ,
                SPEventReceiverType.ItemUncheckingOut ,
                SPEventReceiverType.ItemUpdated ,
                SPEventReceiverType.ItemUpdating ,
                SPEventReceiverType.ItemVersionDeleted ,
                SPEventReceiverType.ItemVersionDeleting };

            web.RemoveListItemEventReceiverFromAllLists(eventReceiverType, allListItemEvents);
        }
    }
}
